package smashedapples.data.feeds
{
	import mx.events.FlexEvent;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;

	import smashedapples.core.NonVisualComponent;



	[Event( name="result",type="mx.rpc.events.ResultEvent" )]
	[Event( name="fault",type="mx.rpc.evnets.FaultEvent" )]


	public class RemoteXML extends NonVisualComponent
	{
		public function RemoteXML()
		{
			super();
			this.addEventListener( FlexEvent.CREATION_COMPLETE, handleCreationComplete );
		}


		private function handleCreationComplete( event:FlexEvent ):void
		{
			if( this.loadOnStart )
				this.send();
		}


		[Bindable]
		public var result:XML;


		public var loadOnStart:Boolean = false;

		public var debug:Boolean = false;

		private var _url:String;


		public function get url():String
		{
			return this._url;
		}

		public function set url( value:String ):void
		{
			this._url = value;
			this.addPropertyChanged( "url" );
		}

		public function onCommitUrl():void
		{
			if( url != null && url != "" )
				this.send();
		}




		public function send():AsyncToken
		{
			var service:HTTPService = new HTTPService();
			service.url = this.url;
			service.addEventListener( FaultEvent.FAULT, handleFaultEvent );
			service.addEventListener( ResultEvent.RESULT, handleResultEvent );
			service.resultFormat = "e4x";
			return service.send();
		}

		private function handleResultEvent( event:ResultEvent ):void
		{
			this.result = event.result as XML;
			this.dispatchEvent( event );

			handleDebug( "RemoteXML.Result", event.result );
		}


		private function handleFaultEvent( event:FaultEvent ):void
		{
			this.dispatchEvent( event );
			handleDebug( "RemoteXML.Fault", event.fault );
		}

		private function handleDebug( type:String, obj:* ):void
		{
			if( this.debug )
				Debug.push( type, obj );
		}


	}
}